<template>
    <div class="upload-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>视频上传</span>
                </div>
            </template>

            <el-upload class="upload-demo" drag action="/api/upload/video" multiple :before-upload="beforeUpload"
                :on-success="handleSuccess" :on-error="handleError" :show-file-list="true" :file-list="fileList"
                :limit="3" :on-exceed="handleExceed" accept="video/*">
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                    将视频文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                    <div class="el-upload__tip">
                        请上传交通监控视频文件，支持MP4、AVI等格式，单文件不超过500MB
                    </div>
                </template>
            </el-upload>

            <div class="process-info" v-if="processing">
                <el-progress :percentage="progressPercent" :status="progressStatus" />
                <div class="process-message">{{ processMessage }}</div>
            </div>

            <div class="result-section" v-if="resultData">
                <h3>分析结果</h3>
                <el-table :data="resultData.violations" border style="width: 100%">
                    <el-table-column prop="time" label="时间点" width="120">
                        <template #default="{ row }">
                            {{ formatTime(row.time) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="plateNumber" label="车牌号" width="120" />
                    <el-table-column prop="type" label="违法类型" width="120">
                        <template #default="{ row }">
                            <el-tag :type="getViolationTag(row.type)">
                                {{ row.type }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="confidence" label="置信度" width="120">
                        <template #default="{ row }">
                            {{ (row.confidence * 100).toFixed(2) }}%
                        </template>
                    </el-table-column>
                    <el-table-column prop="image" label="证据截图">
                        <template #default="{ row }">
                            <el-image style="width: 100px; height: 60px" :src="row.image"
                                :preview-src-list="[row.image]" fit="cover" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #default="{ row }">
                            <el-button size="small" @click="handleCreateCase(row)">创建案件</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { uploadVideo, processVideo, getProcessResult } from '@/api/upload'

const fileList = ref([])
const processing = ref(false)
const progressPercent = ref(0)
const progressStatus = ref('')
const processMessage = ref('')
const resultData = ref(null)

const beforeUpload = (file) => {
    const isVideo = file.type.startsWith('video/')
    const isLt500M = file.size / 1024 / 1024 < 500

    if (!isVideo) {
        ElMessage.error('只能上传视频文件!')
        return false
    }
    if (!isLt500M) {
        ElMessage.error('视频文件大小不能超过500MB!')
        return false
    }

    return true
}

const handleSuccess = (response, file) => {
    ElMessage.success('上传成功，开始分析视频...')
    startProcessing(file)
}

const handleError = (error) => {
    ElMessage.error(`上传失败: ${error.message}`)
}

const handleExceed = () => {
    ElMessage.warning('一次最多上传3个视频文件')
}

const startProcessing = async (file) => {
    processing.value = true
    progressPercent.value = 0
    progressStatus.value = ''
    processMessage.value = '视频上传完成，开始分析...'

    try {
        // 模拟处理进度
        const interval = setInterval(() => {
            progressPercent.value += Math.floor(Math.random() * 5) + 1
            if (progressPercent.value >= 100) {
                clearInterval(interval)
                progressPercent.value = 100
                processMessage.value = '分析完成'
                progressStatus.value = 'success'
                fetchResult(file.response.data.taskId)
            } else if (progressPercent.value < 30) {
                processMessage.value = '视频解码中...'
            } else if (progressPercent.value < 70) {
                processMessage.value = '目标检测中...'
            } else {
                processMessage.value = '违法行为识别中...'
            }
        }, 500)

        // 实际处理
        await processVideo({ fileId: file.response.data.fileId })
    } catch (error) {
        clearInterval(interval)
        progressStatus.value = 'exception'
        processMessage.value = '分析失败: ' + error.message
        ElMessage.error('视频分析失败: ' + error.message)
    }
}

const fetchResult = async (taskId) => {
    try {
        const res = await getProcessResult({ taskId })
        resultData.value = res.data
        ElMessage.success('视频分析完成，发现' + res.data.violations.length + '条违法行为')
    } catch (error) {
        ElMessage.error('获取分析结果失败: ' + error.message)
    }
}

const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
}

const getViolationTag = (type) => {
    const map = {
        '闯红灯': 'danger',
        '超速': 'warning',
        '逆行': 'primary',
        '其他': 'info'
    }
    return map[type] || 'info'
}

const handleCreateCase = (violation) => {
    // 调用API创建案件
    ElMessage.success('案件创建成功')
}
</script>

<style scoped>
.upload-container {
    padding: 20px;
}

.card-header {
    font-size: 16px;
    font-weight: bold;
}

.upload-demo {
    margin-bottom: 20px;
}

.process-info {
    margin-top: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
}

.process-message {
    margin-top: 10px;
    font-size: 14px;
    color: #666;
}

.result-section {
    margin-top: 30px;
}

.result-section h3 {
    margin-bottom: 15px;
    font-size: 16px;
    color: #333;
}
</style>